import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))

import requests
import json
from reqapi.api import BaseApi
from typing import List, Dict

class QueryOffersStatusApi(BaseApi):
    def execute(self, send_order_no_list: List[str]) -> Dict:
        """
        查询报价状态API
        
        Args:
            send_order_no_list: 需要查询的订单号列表
            
        Returns:
            dict: 包含以下字段的字典：
                - totalNum: 总数量
                - sendSuccessNum: 发送成功数量
                - sendFailedNum: 发送失败数量
                - confirmSuccessNum: 确认成功数量
                - confirmFailedNum: 确认失败数量
                - offerIngNum: 报价中数量
                - offerNeedTokenNum: 需要令牌的报价数量
                - offerMessagesList: 报价消息列表
                - sendOfferMessagesList: 发送报价消息列表
        """
        url = f"{self.BASE_URL}/api/youpin/bff/trade/v1/order/sell/delivery/queryOffersStatus"
        data = {
            "sendOrderNoList": send_order_no_list,
            "Sessionid": self.device_id
        }
        headers = self.common_headers.copy()
        print("\n=== 请求信息 ===")
        print(f"请求URL: {url}")
        print(f"请求方法: POST")
        print(f"请求头: {json.dumps(headers, indent=2, ensure_ascii=False)}")
        print(f"请求数据: {json.dumps(data, indent=2, ensure_ascii=False)}")
        try:
            response = self.interceptor.send_request(url, json=data, headers=headers, need_encrypt=False)
            print("\n=== 响应信息 ===")
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print(f"响应数据: {json.dumps(result, indent=2, ensure_ascii=False)}")
            if result.get('code') != 0:
                print(f"API返回错误: {result.get('msg', '未知错误')}")
                return None
            data = result.get('data', {})
            return {
                'totalNum': data.get('totalNum', 0),
                'sendSuccessNum': data.get('sendSuccessNum', 0),
                'sendFailedNum': data.get('sendFailedNum', 0),
                'confirmSuccessNum': data.get('confirmSuccessNum', 0),
                'confirmFailedNum': data.get('confirmFailedNum', 0),
                'offerIngNum': data.get('offerIngNum', 0),
                'offerNeedTokenNum': data.get('offerNeedTokenNum', 0),
                'offerMessagesList': data.get('offerMessagesList', []),
                'sendOfferMessagesList': data.get('sendOfferMessagesList', [])
            }
        except Exception as e:
            print(f"请求发生错误: {str(e)}")
            return None


def main():
    """测试查询报价状态API"""
    try:
        # 使用实际的认证信息
        from com.db.order_account_manager import OrderAccountManager
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
        
        if not account:
            print("无法获取ID为1的账号")
            return
        
        device_id = account.get('device_id', '')
        auth_token = account.get('uu_token', '')
        uk = account.get('uk', '')
        
        # 创建API实例
        api = QueryOffersStatusApi(
            device_token=device_id,  # 使用 device_id 作为 device_token
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 需要查询的订单号列表
        send_order_no_list = [
            "2025020210964853469",
            "2025020210964853470"
        ]
        
        # 调用API
        result = api.execute(send_order_no_list)
        
        # 打印结果
        print("\n=== 查询报价状态结果 ===")
        if result is None:
            print("报价状态查询失败，可能是登录信息失效或接口返回错误。")
        else:
            print(f"总数量: {result['totalNum']}")
            print(f"发送成功数量: {result['sendSuccessNum']}")
            print(f"发送失败数量: {result['sendFailedNum']}")
            print(f"确认成功数量: {result['confirmSuccessNum']}")
            print(f"确认失败数量: {result['confirmFailedNum']}")
            print(f"报价中数量: {result['offerIngNum']}")
            print(f"需要令牌的报价数量: {result['offerNeedTokenNum']}")
            print(f"报价消息列表: {result['offerMessagesList']}")
            print(f"发送报价消息列表: {result['sendOfferMessagesList']}")
    except Exception as e:
        print(f"测试失败: {str(e)}")


if __name__ == "__main__":
    main()
